package thread.semaphore;

import thread.Worker;

/**
 * 测试试用一下semaphore
 * 【信号器做限流那是真不错】
 *
 * @author wei.yang on 2018/8/7
 */
public class ConditionQueue {

    private static final int CYCLIC_TIMES = 30;

    public static void main(String[] args) {
        semaphore();
    }

    /**
     * semaphore测试：
     * semaphore相当于一个线程限流器
     */
    private static void semaphore() {
        Resource resource = new Resource();
        for (int i = 0; i < CYCLIC_TIMES; i++) {
            semaphoreCondition(resource);
        }
    }

    /**
     * 需要执行的任务
     *
     * @param resource 资源信息
     */
    private static void semaphoreCondition(Resource resource) {
        Worker.getWorker().execute(() -> {
            try {
                Model model = resource.useResource();
                if (model != null) {
                    System.out.println(Thread.currentThread().getName() + "\t" + model + "\t" + System.currentTimeMillis());
                    Thread.sleep(10000);
                    resource.release(model);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }
}
